package com.ydd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.dto.*;
import com.ydd.entity.SysUser;

import com.ydd.exception.BaseException;
import com.ydd.mapper.RoleMapper;
import com.ydd.mapper.SysUserMapper;

import com.ydd.result.HMPageResult;
import com.ydd.result.PageResult;
import com.ydd.service.ISysUserService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ydd.vo.UserRoleVO;
import com.ydd.vo.UserRowInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hgz
 * @since 2023-05-30
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public SysUser login(SysUserLoginDTO userLoginDTO) {
        String login_name = userLoginDTO.getLogin_name();
        String password = userLoginDTO.getPassword();

        //根据用户名查询数据库中的数据
        SysUser sysUser = sysUserMapper.getByUsername(login_name);

        //处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (sysUser == null) {
            //账号不存在
            throw new BaseException("账号不存在");
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //使用spring框架提供的api: DigestUtils.md5DigestAsHex(字节数组) 获取md5加盐加密的密文
        password = DigestUtils.md5DigestAsHex((password).getBytes());
        if (!password.equals(sysUser.getPassword())) {
            //密码错误
            throw new BaseException("密码错误");
        }

        //3、返回实体对象
        return sysUser;
    }



    @Override
    public SysUser login(UserLoginDTO userLoginDTO) {
        String login_name = userLoginDTO.getLogin_name();
        String password = userLoginDTO.getPassword();

        //根据用户名查询数据库中的数据
        SysUser sysUser = sysUserMapper.getByUsername(login_name);

        //处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (sysUser == null) {
            //账号不存在
            throw new BaseException("账号不存在");
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //使用spring框架提供的api: DigestUtils.md5DigestAsHex(字节数组) 获取md5加盐加密的密文
        password = DigestUtils.md5DigestAsHex((password).getBytes());
        if (!password.equals(sysUser.getPassword())) {
            //密码错误
            throw new BaseException("密码错误");
        }

        //3、返回实体对象
        return sysUser;
    }


    /**
     * 用户列表分页查询
     *
     * @param sysUserDTO
     * @return
     */
    @Override
    public HMPageResult<UserRoleVO> pageQuery(SysUserDTO sysUserDTO) {
        //设置分页参数
        PageHelper.startPage(sysUserDTO.getPage(), sysUserDTO.getLimit());
        //执行查询
        Page<SysUser> page = sysUserMapper.pageQuery(sysUserDTO);
        // 分页结果数据
        List<SysUser> list = page.getResult();
        // 响应数据
        HMPageResult<UserRoleVO> result = new HMPageResult<>();
        // 转换数据
        List<UserRoleVO> resuleList = new ArrayList<>();
        list.forEach(user -> {
            String roleId = user.getRoleId();
            String[] split = roleId.replace("[", "")
                    .replace("]", "")
                    .replace("\"", "")
                    .split(",");
            List<String> roleidList = Arrays.asList(split);

            List<String> rolename = roleMapper.findByIds(roleidList);
            UserRoleVO ur = new UserRoleVO();
            BeanUtils.copyProperties(user, ur);
            ur.setLogin_name(user.getLoginName());

            ur.setLogin_ip(user.getLoginIp());
            ur.setLogin_date(user.getLoginDate());
            ur.setCreate_date(user.getDefaultData());
            ur.setUpdate_date(user.getDefaultData());
            ur.setDel_flag(user.getDelFlag());
            ur.setDefault_data(user.getDefaultData());
            ur.setRolename(rolename);

            //String roleName = roleMapper.findNameById(user.getRoleId());
            //
            //ur.setRole_id(Lists.newArrayList(user.getRoleId()));
            //ur.setRolename(Lists.newArrayList(roleName));

            resuleList.add(ur);
        });

        // 当前页
        result.setCurrentPage(sysUserDTO.getPage());
        // 总页数
        result.setTotalPage(page.getPages());
        // 分页数据
        result.setData(resuleList);
        // 总数
        result.setCount((int)page.getTotal());
        // 页大小
        result.setPageSize(page.getPageSize());

        // 返回
        return result;
    }


    /**
     * 管理员添加
     *
     * @param sysUserAddDTO
     */
    @Override
    public void addUser(SysUserAddDTO sysUserAddDTO) {

        //
        SysUser sysUser = new SysUser();

        //把sysUserAddDTO赋值给sysUser
        BeanUtils.copyProperties(sysUserAddDTO, sysUser);

        //把roleId转成字符串存到数据库
        sysUser.setRoleId(sysUserAddDTO.getRole_id().toString());

        //获取时间
        LocalDateTime createDate = LocalDateTime.now();
        LocalDateTime updateDate = LocalDateTime.now();
        sysUser.setCreateDate(createDate);
        sysUser.setUpdateDate(updateDate);

        //生成id
        String uuid = UUID.randomUUID().toString();
        sysUser.setId(uuid);

        sysUserMapper.addUser(sysUser);
    }


    /**
     * 管理员删除
     *
     * @param id
     */
    @Override
    public void SysUserdelect(String id) {

        sysUserMapper.SysUserdelect(id);
    }


    /**
     * 管理员详情
     *
     * @return
     */
    @Override
    public UserRowInfoVO UserRowInfo(String id) {

        SysUser sysUse = sysUserMapper.UserRowInfo(id);

        UserRowInfoVO us = new UserRowInfoVO();
        BeanUtils.copyProperties(sysUse, us);
        us.setLogin_name(sysUse.getLoginName());
        us.setPassword("");

        //获取role_id
        String roleId = sysUse.getRoleId();
        String[] split = roleId.replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> roleidList = Arrays.asList(split);
        us.setRoleId(roleidList);

        //获取时间
        us.setCreateDate(LocalDateTime.now().toString());

        return us;
    }


    /**
     * 管理员修改
     * @param sysUpdateDTO
     */
    @Override
    public void UserUpdate(SysUpdateDTO sysUpdateDTO) {

        //获取时间
        sysUpdateDTO.setCreateDate(LocalDateTime.now());
        sysUpdateDTO.setUpdateDate(LocalDateTime.now());


        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUpdateDTO,sysUser);
        sysUser.setRoleId(sysUpdateDTO.getRoleId().toString());
        //返回数据
        sysUserMapper.userUpdate(sysUser);

    }
}
